package com.ray.wms.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ray.common.SysMsgCodeConstant;
import com.ray.util.StringUtil;
import com.ray.wms.builder.WarehouseStockBuilder;
import com.ray.wms.builder.WarehouseStockDetailBuilder;
import com.ray.wms.table.dto.GoodsDTO;
import com.ray.wms.table.dto.StockQueryDTO;
import com.ray.wms.table.entity.WmsOrderAllot;
import com.ray.wms.table.entity.WmsWarehouse;
import com.ray.wms.table.entity.WmsWarehouseStock;
import com.ray.wms.table.entity.WmsWarehouseStockDetail;
import com.ray.wms.table.mapper.WmsWarehouseStockDetailMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ray.woodencreate.beans.BeanCreate;
import com.ray.woodencreate.beans.CommonValue;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import com.ray.woodencreate.mybatis.DataAuthUtil;
import com.ray.woodencreate.page.CommonPage;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Length;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotBlank;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 仓库库存明细 服务实现类
 * </p>
 *
 * @author shenbo
 * @since 2020-06-02
 */
@Service
@Slf4j
public class WmsWarehouseStockDetailService extends ServiceImpl<WmsWarehouseStockDetailMapper, WmsWarehouseStockDetail> {


    /**
     * 列表查询
     *
     * @param queryParams
     * @param loginUser
     * @return
     */
    public IPage<WmsWarehouseStockDetail> page(CommonPage<StockQueryDTO, Page<WmsWarehouseStockDetail>> queryParams, LoginUser loginUser) {
        StockQueryDTO params = queryParams.getEntity();
        WmsWarehouseStockDetail entity = BeanCreate.newBean(WmsWarehouseStockDetail.class);
        //查询对象存在
        if (ObjectUtil.isNotNull(params)) {
            if (params.getAllData() && StrUtil.equals(params.getBusinessOrderNo(), CommonValue.DEFAULT_ZERO)) {
                params.setBusinessOrderNo(null);
            }
            BeanUtil.copyProperties(params, entity);
        }
        QueryWrapper<WmsWarehouseStockDetail> queryWrapper = new QueryWrapper<>(entity);
        queryWrapper.gt("quantity", new BigDecimal(0));
        queryWrapper.orderByDesc("create_time");
        queryWrapper.in(ObjectUtil.isNotEmpty(params.getModelCodes()), "goods_code", params.getModelCodes());
        DataAuthUtil.addComapnyDataAuth(queryWrapper, loginUser);
        return page(queryParams.getPage(), queryWrapper);
    }

    public boolean addDetail(GoodsDTO goodsDTO, LoginUser loginUser) {
        //查询记录
        WmsWarehouseStockDetail wmsWarehouseStock = query(goodsDTO, loginUser);
        if (ObjectUtil.isNull(wmsWarehouseStock)) {
            if (goodsDTO.getQuantity().compareTo(new BigDecimal(0)) < 0) {
                log.info("库存不够,{},{}", JSON.toJSONString(goodsDTO), JSON.toJSONString(wmsWarehouseStock));
                throw BusinessExceptionFactory.newException("库存不足");
            }
            //没有库存插入库存数据
            return save(new WarehouseStockDetailBuilder().append(goodsDTO).appendCreate(loginUser).bulid());
        } else {
            if (wmsWarehouseStock.getQuantity().add(goodsDTO.getQuantity()).compareTo(new BigDecimal(0)) < 0) {
                log.info("库存不够,{},{}", JSON.toJSONString(goodsDTO), JSON.toJSONString(wmsWarehouseStock));
                throw BusinessExceptionFactory.newException("库存不足");
            }
            WmsWarehouseStockDetail entity = new WmsWarehouseStockDetail();
            entity.setQuantity(wmsWarehouseStock.getQuantity().add(goodsDTO.getQuantity()));
            entity.setTotal(Math.max(wmsWarehouseStock.getTotal() + goodsDTO.getTotal(),0));
            entity.setUpdateVersion(wmsWarehouseStock.getUpdateVersion() + 1);
            WmsWarehouseStockDetail query = new WmsWarehouseStockDetail();
            query.setWarehouseCode(goodsDTO.getWarehouseCode());
            query.setGoodsCode(goodsDTO.getGoodsCode());
            query.setBatchNo(goodsDTO.getBatchNo());
            query.setSerialNumber(goodsDTO.getSerialNumber());
            query.setUpdateVersion(wmsWarehouseStock.getUpdateVersion());
            query.setBusinessOrderNo(goodsDTO.getOrderNo());
            query.setUnit(goodsDTO.getUnit());
            UpdateWrapper<WmsWarehouseStockDetail> updateWrapper = new UpdateWrapper<>(query);
            DataAuthUtil.addComapnyDataAuth(updateWrapper, loginUser);
            return update(entity, updateWrapper);
        }
    }

    /**
     * 查询库存记录
     *
     * @param goodsDTO
     * @param loginUser
     * @return
     */
    public WmsWarehouseStockDetail query(GoodsDTO goodsDTO, LoginUser loginUser) {
        WmsWarehouseStockDetail query = new WmsWarehouseStockDetail();
        query.setGoodsCode(goodsDTO.getGoodsCode());
        query.setWarehouseCode(goodsDTO.getWarehouseCode());
        query.setBatchNo(goodsDTO.getBatchNo());
        query.setSerialNumber(StringUtil.nullToEmpty(goodsDTO.getSerialNumber()));
        query.setBusinessOrderNo(goodsDTO.getOrderNo());
        query.setUnit(goodsDTO.getUnit());
        QueryWrapper<WmsWarehouseStockDetail> queryWrapper = new QueryWrapper<>(query);
        DataAuthUtil.addComapnyDataAuth(queryWrapper, loginUser);
        return getOne(queryWrapper);
    }

    /**
     * 获取记录
     *
     * @param code
     * @param loginUser
     * @return
     */
    public WmsWarehouseStockDetail queryByCode(String code, LoginUser loginUser) {
        WmsWarehouseStockDetail query = new WmsWarehouseStockDetail();
        query.setStockCode(code);
        QueryWrapper<WmsWarehouseStockDetail> queryWrapper = new QueryWrapper<>(query);
        DataAuthUtil.addComapnyDataAuth(queryWrapper, loginUser);
        return getOne(queryWrapper);
    }

    public boolean changeBusinessOrder(String newOrderNo, String code, Integer updateVersion, LoginUser loginUser) {
        WmsWarehouseStockDetail entity = new WmsWarehouseStockDetail();
        entity.setBusinessOrderNo(newOrderNo);
        entity.setUpdateVersion(updateVersion + 1);
        WmsWarehouseStockDetail query = new WmsWarehouseStockDetail();
        query.setStockCode(code);
        query.setUpdateVersion(updateVersion);
        UpdateWrapper<WmsWarehouseStockDetail> updateWrapper = new UpdateWrapper<>(query);
        DataAuthUtil.addComapnyDataAuth(updateWrapper, loginUser);
        return update(entity, updateWrapper);
    }

    /**
     * 查询商品是否存在
     *
     * @param goodsCode
     * @param serialNumber
     * @param loginUser
     * @return
     */
    public WmsWarehouseStockDetail existByGoodsCodeAndNumber(String goodsCode, String serialNumber, LoginUser loginUser) {
        if (StrUtil.isBlank(serialNumber)) {
            return null;
        }
        WmsWarehouseStockDetail query = new WmsWarehouseStockDetail();
        query.setGoodsCode(goodsCode);
        query.setSerialNumber(serialNumber);
        QueryWrapper<WmsWarehouseStockDetail> queryWrapper = new QueryWrapper<>(query);
        queryWrapper.gt("quantity", new BigDecimal(0));
        DataAuthUtil.addComapnyDataAuth(queryWrapper, loginUser);
        return getOne(queryWrapper);
    }

    public List<WmsWarehouseStockDetail> list(GoodsDTO goodsDTO, LoginUser loginUser) {
        WmsWarehouseStockDetail query = new WmsWarehouseStockDetail();
        query.setGoodsCode(goodsDTO.getGoodsCode());
        query.setWarehouseCode(goodsDTO.getWarehouseCode());
        query.setBusinessOrderNo(goodsDTO.getOrderNo());
        query.setBatchNo(goodsDTO.getBatchNo());
        query.setSerialNumber(goodsDTO.getSerialNumber());
        query.setUnit(goodsDTO.getUnit());
        QueryWrapper<WmsWarehouseStockDetail> queryWrapper = new QueryWrapper<>(query);
        DataAuthUtil.addComapnyDataAuth(queryWrapper, loginUser);
        return list(queryWrapper);
    }
}
